import { defineStore } from 'pinia'
import useFiltersStore from './filters'

// 定义仓库
// useTodosStore()
const useTodosStore = defineStore('todos', {
  state() {
    // state是个函数的优势: 如果你的数据初始值是需要一定的js逻辑处理得到的
    const initValue = JSON.parse(localStorage.getItem('todos-pinia')) || []

    return {
      list: initValue,
    }
  },

  actions: {
    // 所有修改仓库数据的方式 全都在这!!! 将来好定位问题 调试代码
    changeDone(id) {
      const todo = this.list.find((item) => item.id === id)
      todo.done = !todo.done
    },
    delTodo(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    addTodo(name) {
      this.list.unshift({
        id: Date.now(),
        name,
        done: false,
      })
    },
    changeAll(flag) {
      this.list.forEach((item) => {
        item.done = flag
      })
    },
    clearDone() {
      this.list = this.list.filter((item) => !item.done)
    },
  },

  getters: {
    isAllChecked() {
      return this.list.every((item) => item.done)
    },
    isShowFooter() {
      return this.list.length > 0
    },
    leftCount() {
      return this.list.filter((item) => !item.done).length
    },
    isShowClear() {
      return this.list.some((item) => item.done)
    },
    // 用于中间组件的展示
    showList() {
      // return this.list
      const filters = useFiltersStore()
      if (filters.active === 'All') {
        return this.list
      } else if (filters.active === 'Active') {
        return this.list.filter((item) => !item.done)
      } else {
        return this.list.filter((item) => item.done)
      }
    },
  },
})

export default useTodosStore
